package com.liezh.proxy.dynamicproxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 使用jdk动态代理，核心是InvocationHandler interface
 * @author liezh
 * @date 2021-5-26
 */
public class JdkProxy implements InvocationHandler {

    // 真正的业务对象
    private Object realObj;

    public JdkProxy(Object realObj) {
        this.realObj = realObj;
    }

    /**
     * realObj方法前后添加额外的扩展逻辑
     * @param proxy
     * @param method
     * @param args
     * @return
     * @throws Throwable
     */
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 额外的业务逻辑
        System.out.println("before");
        Object result = method.invoke(realObj, args);
        System.out.println("after");
        // 额外的业务逻辑
        return result;
    }

    public Object getProxy() {
        // 创建代理对象，使用当前线程的类加载器，反射创建代理对象
        return Proxy.newProxyInstance(Thread.currentThread()
                        .getContextClassLoader(),
                realObj.getClass().getInterfaces(), this);
    }

}
